package produce.controller;

import com.alibaba.fastjson2.util.DateUtils;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * @author Kevin
 * @date 2023/6/11 12:49
 * @description 延时消息
 **/
@RequestMapping("/ttl")
@RestController
public class TtlController {

  @Autowired
  private RabbitTemplate rabbitTemplate;

  /**
   * 发送延迟消息
   * @param msg 消息内容
   * @param key 路由key
   * @param ttlTime 过期时间（ms）
   * @return
   */
  @GetMapping
  public String send(String msg,String key,String ttlTime){
    // 可以自定义消息过期时间，优先级要大于队列时间
//    MessageProperties messageProperties = new MessageProperties();
//    messageProperties.setExpiration(ttlTime); // 过期时间，毫秒
//    rabbitTemplate.convertAndSend("ttl-exchange", key, MessageBuilder
//            .withBody(msg.getBytes(StandardCharsets.UTF_8))
//            .andProperties(messageProperties).build());

    rabbitTemplate.convertAndSend("ttl-exchange", key,msg);
    return DateUtils.format(new Date(), "yyyy-dd-MM HH:mm:ss")+"发送延时的消息成功";
  }

}
